package me.zhengjie.modules.common.service.impl;

import me.zhengjie.modules.common.domain.TRegion;
import me.zhengjie.modules.common.service.dto.TRegionDTO;
import me.zhengjie.modules.common.repository.TRegionRepository;
import me.zhengjie.modules.common.service.TRegionService;
import me.zhengjie.modules.common.service.dto.TRegionQueryCriteria;
import me.zhengjie.modules.common.service.mapper.TRegionMapper;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * Created by bruce on 2021/4/23.
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TRegionServiceImpl implements TRegionService {

    @Autowired
    private TRegionRepository tRegionRepository;

    @Autowired
    private TRegionMapper tRegionMapper;


    @Override
    public TRegionDTO create(TRegion resources) {
        return tRegionMapper.toDto(tRegionRepository.save(resources));
    }

    @Override
    public Object queryAll(TRegionQueryCriteria criteria, Pageable pageable) {
        Page<TRegion> page = tRegionRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(tRegionMapper::toDto));
    }

    @Override
    public Object queryAll(TRegionQueryCriteria criteria) {
        return tRegionMapper.toDto(tRegionRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public TRegion findByName(String name) {
        return tRegionRepository.findByName(name);
    }

    @Override
    public TRegionDTO findById(Long id) {
        Optional<TRegion> regionOptional = tRegionRepository.findById(id);
        ValidationUtil.isNull(regionOptional, "TRegion", "id", id);
        return tRegionMapper.toDto(regionOptional.get());
    }

    @Override
    public void update(TRegion resources) {
        tRegionRepository.save(resources);
    }

    @Override
    public void delete(Long id) {
        tRegionRepository.deleteById(id);
    }
}
